import logging
import sys
from datetime import datetime
from pathlib import Path

from config.settings import LOG_FILE_PREFIX, LOGS_DIR

# ==================== 配置区 ====================
DEBUG_MODE = True

LOG_DIR = LOGS_DIR

current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
LOG_FILE = LOG_DIR / f"{LOG_FILE_PREFIX}_{current_time}.log"
# =================================================


class SafeFormatter(logging.Formatter):
    """
    安全的日志格式化器：自动补全缺失的自定义字段（如 src_file, src_line）
    避免因 missing field 导致的 ValueError
    """
    def format(self, record):
        # 确保 src_file 存在
        if not hasattr(record, 'src_file'):
            record.src_file = getattr(record, 'filename', 'unknown')  # fallback 到 filename 或 unknown
        # 确保 src_line 存在
        if not hasattr(record, 'src_line'):
            record.src_line = getattr(record, 'lineno', 0)
        return super().format(record)


def get_caller_info():
    """
    获取调用当前函数上一层代码位置（文件名、行号）
    返回 (filename, lineno)
    """
    frame = sys._getframe(2)  # 0: 当前, 1: log_xxx, 2: 用户代码
    filename = Path(frame.f_code.co_filename).name
    lineno = frame.f_lineno
    return filename, lineno


def setup_logger():
    """
    设置全局日志器
    """
    app_logger = logging.getLogger("LabelRelationTest")
    app_logger.setLevel(logging.DEBUG)

    # 防止重复添加 handler
    if app_logger.handlers:
        return app_logger

    # 使用 SafeFormatter
    formatter = SafeFormatter(
        '[%(asctime)s] %(levelname)s: [%(src_file)s:%(src_line)d] - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )

    # 文件处理器：带详细位置信息
    file_handler = logging.FileHandler(LOG_FILE, encoding='utf-8', mode='w')
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)

    # 控制台处理器：简洁输出（仅消息）
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)  # 控制台只显示 INFO 及以上
    console_formatter = logging.Formatter('%(message)s')
    console_handler.setFormatter(console_formatter)

    app_logger.addHandler(file_handler)
    app_logger.addHandler(console_handler)
    return app_logger


# 获取日志器实例
logger = setup_logger()


# ========== 封装的日志函数（自动注入调用位置）==========
def log_info(msg):
    """记录信息日志"""
    filename, lineno = get_caller_info()
    logger.info(msg, extra={'src_file': filename, 'src_line': lineno})


def log_error(msg):
    """记录错误日志"""
    filename, lineno = get_caller_info()
    logger.error(msg, extra={'src_file': filename, 'src_line': lineno})


def log_warning(msg):
    """记录警告日志"""
    filename, lineno = get_caller_info()
    logger.warning(msg, extra={'src_file': filename, 'src_line': lineno})


def log_debug(msg):
    """记录调试日志（受 DEBUG_MODE 控制）"""
    if DEBUG_MODE:
        filename, lineno = get_caller_info()
        logger.debug(msg, extra={'src_file': filename, 'src_line': lineno})